<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">

      <a-form-item class="smart-query-form-item" label="所属品牌">
        <a-select v-model:value="queryForm.brandId" allowClear placeholder="选择品牌" style="width: 160px">
          <a-select-option v-for="option in brandOptions" :value="option.id">{{ option.brandName }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item class="smart-query-form-item" label="所属品类">
        <a-select v-model:value="queryForm.category" allowClear placeholder="选择品类" style="width: 160px">
          <a-select-option value="1">手机</a-select-option>
          <a-select-option value="2">平板</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="型号名称">
        <a-input v-model:value="queryForm.modelName" placeholder="型号名称" style="width: 160px"/>
      </a-form-item>


      <a-form-item class="smart-query-form-item" label="更新时间">
        <a-space :size="12" direction="vertical">
          <a-range-picker v-model:value="searchDate" :ranges="defaultTimeRanges" @change="dateChange"/>
        </a-space>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="add()">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增型号
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :pagination="false"
        :scroll="{ x: 1300 }"
        bordered
        rowKey="enterpriseId"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'icon'">
          <a-image
              :src="text"
              :width="80"
          />
        </template>
        <template v-if="column.dataIndex === 'category'">
          {{ text === 1 ? '手机' : text === 2 ? '平板' : '未知' }}
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="update(record)">编辑</a-button>
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>
  <!--  添加和修改对话框-->
  <a-modal :title="`${formData.id?'编辑':'新增'}型号`" :visible="modalVisible" @cancel="onClose" @ok="handleOk">

    <a-form ref="formRef" :label-col="labelCol" :model="formData" :rules="rules" :wrapper-col="wrapperCol">
      <a-form-item label="型号名称" name="modelName">
        <a-input v-model:value="formData.modelName" placeholder="请输入型号名称"/>
      </a-form-item>

      <a-form-item label="所属品牌" name="brandId">
        <a-select v-model:value="formData.brandId" allowClear placeholder="选择品牌" style="width: 120px">
          <a-select-option v-for="option in brandOptions" :value="option.id">{{ option.brandName }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="所属品类" name="category">
        <a-select v-model:value="formData.category" allowClear placeholder="选择品类" style="width: 120px">
          <a-select-option :value="1">手机</a-select-option>
          <a-select-option :value="2">平板</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="图片">
        <FileUpload
            :defaultFileList="defaultImgList.arr"
            :folder="FILE_FOLDER_TYPE_ENUM.MODEL.value"
            :maxUploadSize="1"
            :multiple="true"
            buttonText="点击上传图片"
            list-type="picture-card"
            @change="imgChange"
        />
      </a-form-item>

      <a-form-item label="存储容量">

        <template v-for="tag in formData.memory" :key="tag">
          <a-tag closable color="processing" @close="handleMemoryRemove(tag)">{{ tag }}</a-tag>
        </template>
        <a-input
            v-if="memoryTagState.inputVisible"
            ref="memoryInputRef"
            v-model:value="memoryTagState.inputValue"
            :style="{ width: '78px' }"
            size="small"
            type="text"
            @blur="handleMemoryInputConfirm"
            @keyup.enter="handleMemoryInputConfirm"
        />
        <a-tag v-else style="background: #fff; border-style: dashed" @click="showMemoryInput">
          <plus-outlined/>
          添加
        </a-tag>

      </a-form-item>


      <a-form-item label="颜色">

        <template v-for="tag in formData.color" :key="tag">
          <a-tag closable color="processing" @close="handleColorRemove(tag)">{{ tag }}</a-tag>
        </template>
        <a-input
            v-if="colorTagState.inputVisible"
            ref="colorInputRef"
            v-model:value="colorTagState.inputValue"
            :style="{ width: '78px' }"
            size="small"
            type="text"
            @blur="handleColorInputConfirm"
            @keyup.enter="handleColorInputConfirm"
        />
        <a-tag v-else style="background: #fff; border-style: dashed" @click="showColorInput">
          <plus-outlined/>
          添加
        </a-tag>

      </a-form-item>
    </a-form>
  </a-modal>

</template>


<script setup>
import {defaultTimeRanges} from "/@/lib/default-time-ranges";
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {modelApi} from './model-api';
import {brandApi} from '../brand/brand-api';
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import _ from 'lodash';
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {useRoute} from "vue-router";

const route = useRoute();
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
const rules = {
  modelName: [{required: true, message: '型号名称不能为空'}],
  brandId: [{required: true, message: '请选择所属品牌'}],
  category: [{required: true, message: '请选择所属品类'}],
};

const memoryTagState = reactive({
  inputVisible: false,
  inputValue: '',
});
const colorTagState = reactive({
  inputVisible: false,
  inputValue: '',
});

const formDataDefault = {
  id: '',
  modelName: undefined, //型号名称
  brandId: undefined, //品牌
  category: undefined, //品类
  color: [], //颜色
  memory: [], //容量
  icon: '',
};
let formData = reactive({...formDataDefault});

let defaultImgList = reactive({arr: []});
let brandOptions = ref([]);
// 组件ref
const formRef = ref();
const memoryInputRef = ref();
const colorInputRef = ref();
const columns = ref([
  {
    width: 60,
    align: 'center',
    title: '型号id',
    dataIndex: 'id',
    ellipsis: true,
  },
  {
    width: 80,
    align: 'center',
    title: '型号名称',
    dataIndex: 'modelName',
    ellipsis: true,
  },
  {
    width: 80,
    align: 'center',
    title: '所属品牌',
    dataIndex: 'brandName',
    ellipsis: true,
  },
  {
    width: 80,
    align: 'center',
    title: '所属品类',
    dataIndex: 'category',
    ellipsis: true,
  },
  {
    width: 80,
    align: 'center',
    title: '图标',
    dataIndex: 'icon',
    ellipsis: true,
  },
  {
    width: 100,
    align: 'center',
    title: '更新时间',
    dataIndex: 'updateTime',
    ellipsis: true,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    fixed: 'right'
  },
]);
const queryFormDataDefault = {
  updateTimeBegin: undefined, //修改时间 开始
  updateTimeEnd: undefined, //修改时间 结束
  modelName: undefined, //型号名称
  brandId: undefined, //品牌id
  category: undefined, //品类 1手机 2平板
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();
// 日期选择
let searchDate = ref();
const modalVisible = ref(false);

function dateChange(dates, dateStrings) {
  queryForm.updateTimeBegin = dateStrings[0];
  queryForm.updateTimeEnd = dateStrings[1];
}

// 重置查询条件
function resetQuery() {
  searchDate.value = [];
  Object.assign(queryForm, queryFormDataDefault);
  ajaxQuery();
}

onMounted(() => {
  queryForm.brandId = parseInt(route.query?.brandId) || undefined;
  queryBrand();
  ajaxQuery();
});


// 查询品牌
async function queryBrand() {
  try {
    let responseModel = await brandApi.queryPage({pageNum: 1, pageSize: 200});
    brandOptions.value = responseModel.data.list;
  } catch (e) {
    smartSentry.captureError(e);
  }
}

function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}
// 查询
async function ajaxQuery() {
  try {
    tableLoading.value = true;
    let responseModel = await modelApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// 图片改变
function imgChange(e) {
  console.log(e[0])
  formData.icon = e[0]?.url || '';
}

// 添加
function add() {
  showModal();
}

// 修改
function update(record) {
  Object.assign(formData, {
    id: record.id,
    modelName: record.modelName, //型号名称
    brandId: record.brandId, //品牌
    category: record.category, //品类
    color: record.color ? record.color.split(',') : [], //颜色
    memory: record.memory ? record.memory.split(',') : [], //容量
    icon: record.icon,
  });
  const imgType = record.icon ? record.icon.split('_') : '';
  defaultImgList.arr = record.icon ? [{fileUrl: record.icon, fileType: imgType[imgType.length - 1]}] : [];
  showModal();
}

const showModal = () => {
  modalVisible.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

const handleOk = (e) => {
  save();
};

async function save() {
  formRef.value
      .validate()
      .then(async () => {
        SmartLoading.show();
        const form = _.cloneDeep(formData);
        try {
          form.memory = form.memory.join(',');
          form.color = form.color.join(',');
          if (form.id) {
            await modelApi.update(form);
          } else {
            await modelApi.add(form);
          }
          message.success(`${form.id ? '修改' : '添加'}成功`);
          ajaxQuery();
          onClose();
        } catch (error) {
          smartSentry.captureError(error);
        } finally {
          SmartLoading.hide();
        }
      })
      .catch((error) => {
        console.log('error', error);
        message.error('参数验证错误，请仔细填写表单数据!');
      });
}

function onClose() {
  Object.assign(formData, formDataDefault);
  formData.memory = [];
  formData.color = [];
  defaultImgList.arr = [];
  Object.assign(memoryTagState, {inputVisible: false, inputValue: ''});
  Object.assign(colorTagState, {inputVisible: false, inputValue: ''});
  modalVisible.value = false;
}

// 删除
function confirmDelete(record) {

  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.brandName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

// 确认删除
async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await modelApi.delete(brandData.id);
    message.success('删除成功');
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// 显示内存输入框
const showMemoryInput = () => {
  memoryTagState.inputVisible = true;
  nextTick(() => {
    memoryInputRef.value.focus();
  });
};

// 确认输入内存
function handleMemoryInputConfirm() {
  const inputValue = memoryTagState.inputValue;
  if (inputValue.match(/,/)) {
    message.warning('内存不能包含逗号');
    return;
  }
  let tags = formData.memory;
  if (inputValue && tags.indexOf(inputValue) === -1) {
    tags = [...tags, inputValue];
  }
  Object.assign(formData.memory, [...tags]);
  Object.assign(memoryTagState, {inputVisible: false, inputValue: ''});
}

// 删除内存
function handleMemoryRemove(removedTag) {
  formData.memory = formData.memory.filter(tag => tag !== removedTag);
}

// 显示颜色输入框
const showColorInput = () => {
  colorTagState.inputVisible = true;
  nextTick(() => {
    colorInputRef.value.focus();
  });
};

// 确认输入颜色
function handleColorInputConfirm() {
  const inputValue = colorTagState.inputValue;
  if (inputValue.match(/,/)) {
    message.warning('颜色不能包含逗号');
    return;
  }
  let tags = formData.color;
  if (inputValue && tags.indexOf(inputValue) === -1) {
    tags = [...tags, inputValue];
  }
  Object.assign(formData.color, [...tags]);
  Object.assign(colorTagState, {inputVisible: false, inputValue: ''});
}

// 删除颜色
function handleColorRemove(removedTag) {
  formData.color = formData.color.filter(tag => tag !== removedTag);
}
</script>

<style lang="less" scoped>

</style>